package main

import (
	"net/http"
	"os"
	"os/signal"
	"syscall"

	"github.com/go-chi/chi"
	"github.com/sirupsen/logrus"
	"github.com/urfave/cli"

	"github.com/wi-cuckoo/eastlake/server"
	"github.com/wi-cuckoo/eastlake/web"
	"github.com/wi-cuckoo/eastlake/web/service"
)

var flags = []cli.Flag{
	cli.BoolFlag{
		EnvVar: "EASTLAKE_ENV_DEBUG",
		Name:   "debug",
		Usage:  "enable debug mode",
	},
	cli.StringFlag{
		EnvVar: "EASTLAKE_ADDR",
		Name:   "addr",
		Value:  ":4399",
		Usage:  "address to serve",
	},
	cli.StringFlag{
		EnvVar: "GITLAB_SERVER",
		Name:   "gitlabServer",
		Value:  "https://gitlab.com/",
		Usage:  "oauth2 login",
	},
	cli.StringFlag{
		EnvVar: "GITLAB_CLIENT_ID",
		Name:   "gitlabClientID",
		Value:  "f91e22d0820d75fdeee9f9af1e9b3b95b5cb78272aa67f6f89752ee09ec289df",
		Usage:  "oauth2 login",
	},
	cli.StringFlag{
		EnvVar: "GITLAB_CLIENT_SECRET",
		Name:   "gitlabClientSecret",
		Value:  "cb4f40f569ca3dacfdaf54e738c3f1391793671c4f38a4861a0b4d66fb6504bd",
		Usage:  "oauth2 login",
	},
	cli.StringFlag{
		EnvVar: "EASTLAKE_SQLITE",
		Name:   "sqlite",
		Usage:  "sqlite dsn",
		Value:  "./eastlake.db",
	},
}

func main() {
	app := cli.NewApp()
	app.Name = "eastlake"
	app.Usage = "control plane for drone ci/cd"
	app.Flags = flags
	app.Action = run
	if err := app.Run(os.Args); err != nil {
		logrus.Error("app.Run err: ", err)
	}
}

func run(c *cli.Context) error {
	// set logger
	logrus.SetFormatter(&logrus.TextFormatter{FullTimestamp: true})
	if c.Bool("debug") {
		logrus.SetLevel(logrus.DebugLevel)
		logrus.SetReportCaller(true)
	}

	func() {
		r := chi.NewRouter()
		// 注册 rpc 服务
		rpcSvr := server.NewServer("ojbk")
		r.Mount("/rpc", rpcSvr)
		// 注册 web 服务
		webSvr := web.NewServer("web api for user")
		r.Mount("/", webSvr.Handler())

		// 初始化service
		service.InitService(c)

		http.ListenAndServe(c.String("addr"), r)
	}()

	// 注册退出信号
	s := make(chan os.Signal, 1)
	signal.Notify(s, os.Interrupt, syscall.SIGTERM)
	<-s
	logrus.Info("receive stop signal from system, exited")
	return nil
}
